package com.cn.demo4.servlet.admin.news;

import com.alibaba.fastjson.JSONObject;
import com.cn.demo4.model.NewsModel;
import com.cn.demo4.service.INewsService;
import com.cn.demo4.service.impl.NewsServiceImpl;
import com.cn.demo4.util.LoadImg;
import com.cn.demo4.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/adminFile/news/update")
public class NewsUpdateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.解决乱码(过滤器为过滤文件上传类型的数据，所以要设置编码问题)
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //2.取得前台传递的值
        LoadImg.loadImg(req);
        /**
         * req在文件流的时候只能拿到一次数据，所以也不能进入过滤器
         */
        //如果没有登录则直接返回resp.getWriter().println(jsonObject);
        HttpSession session = req.getSession();
        String key = (String) req.getAttribute("loginPhone");
        String phone = (String) session.getAttribute(key);
        if (phone == null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result", "noLogin");
            resp.getWriter().println(jsonObject);
            return;
        }

        //3.封装数据
        NewsModel newsModel = new NewsModel();
        newsModel.setId(Tool.stringToInt((String)req.getAttribute("id")) );
        newsModel.setTitle((String) req.getAttribute("title"));
        newsModel.setContent((String) req.getAttribute("content"));
        newsModel.setImg((String) req.getAttribute("img"));
        newsModel.setTypeId(Tool.stringToInt((String)req.getAttribute("typeId")) );
        newsModel.setTypeName((String) req.getAttribute("typeName"));
        newsModel.setStatus(Tool.stringToInt((String) req.getAttribute("status")));
        newsModel.setIsShow(Tool.stringToInt((String) req.getAttribute("isShow")));
        newsModel.setPublisher((String) req.getAttribute("publisher"));

        //4.调用服务层
        INewsService iNewsService = new NewsServiceImpl();
        //5.得到结果
        String result = iNewsService.update(newsModel);

        //6.返回结果
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result",result);
        resp.getWriter().println(jsonObject);


    }
}
